//
// Created by 常磊 on 2022/4/4.
//

import Foundation


fileprivate let pattern = "yyyy-MM-dd"

/// 处理日期相关
class Dates {
    private init() {
    }

    static func parse(_ value: String) -> Date {
        trpParse(value)!
    }

    static func trpParse(_ value: String) -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = pattern
        return formatter.date(from: value)
    }

    static func format(_ value: Any, pattern: String = pattern) -> String {
        tryFormat(value, pattern: pattern)!
    }

    static func tryFormat(_ value: Any?, pattern: String = pattern) -> String? {
        assert(value is String || value is Date || value is Double, "只能格式化`Date`和格式化的日期，如`2022-02-02`，还有时间戳")
        let formatter = DateFormatter()
        formatter.dateFormat = pattern
        if let date = value as? Date {
            return formatter.string(from: date)
        } else if let formatted = value as? String {
            return formatter.string(for: trpParse(formatted))
        } else if let timestamp = value as? Double {
            return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp)))
        } else {
            return nil
        }
    }
}